from pyglet.gl import *
import data
import random

class Puzzle:
    tex_size = 512 
    start = -1
    width = 400
    xoffset = -200
    yoffset = -100
    def __init__(self, size):
        self.size = size
        self.bs = Puzzle.width/size 
        self.indices = range(size*size) 
        img = pyglet.image.load(data.filepath('screenshot.png')) 
        (w, h) = (img.width, img.height)
        #get a proper sized image for better picture in puzzle
        puzzle_img = img.get_region(x=w/2-Puzzle.tex_size/2, y=h/2-Puzzle.tex_size/2, width=Puzzle.tex_size, height=Puzzle.tex_size)
        self.tex = puzzle_img.get_texture()
        self.head_msg = pyglet.text.HTMLLabel('<h2><font color=#FFFFFF>Solve the JigSaw Puzzle</font></h2>', x=300, y=80)
        self.tip = pyglet.text.HTMLLabel('<b><font color=#FFFFFF>Click and Drag a Tile to swap (use mouse) </font></b>', x=250, y=50)

        while self.isSolved():
            self.randomize()

        self.verts = ()
        gap = 1
        bs = self.bs
        for i in xrange(size*size):
            x = i % size
            y = i / size
            self.verts += (x*bs+gap, y*bs+gap, (x+1)*bs-gap, y*bs+gap, (x+1)*bs-gap, (y+1)*bs-gap, x*bs+gap, (y+1)*bs-gap)

    def randomize(self):
        #jumble all the  values in puzzle 
        size = self.size
        for i in xrange(size):
            indx = random.randint(0, size*size-1)
            tmp = self.indices[0]
            self.indices[0] = self.indices[indx]
            self.indices[indx] = tmp

    def isSolved(self):
        for i in xrange(len(self.indices)):
            if not(i == self.indices[i]):
                return False
        return True

    def swapIndices(self, i1, i2):
        tmp = self.indices[i2]
        self.indices[i2] = self.indices[i1]
        self.indices[i1] = tmp

        if self.isSolved():
            self.head_msg.text = '<h2><font color=#00ff00>Puzzle Solved!!</font></h2>' 
            self.tip.text = '<b><font color=#ffffff>Click anywhere to Continue (use mouse)</font></b>' 

    def getIndex(self, pos):
        """send pos with origin at left bottom corner"""
        bs = self.bs
        #trivial case where the mouse point is outside the puzzle
        #print pos, self.size * bs
        if pos[0] < 0 or pos[1] > self.size * bs or pos[0] > bs *self.size or pos[1] < 0:
            return -1

        x = pos[0] / bs
        y = pos[1] / bs 
        #print "index: ", y * self.size + x
        return y * self.size + x

    def draw(self, (w, h)):
        glMatrixMode(GL_PROJECTION)
        glPushMatrix()
        glLoadIdentity()
        #gluOrtho2D(-300, w-300, -100, h-100)
        gluOrtho2D(Puzzle.xoffset, w+Puzzle.xoffset, Puzzle.yoffset, h+Puzzle.yoffset)
        glMatrixMode(GL_MODELVIEW)
        glPushMatrix()
        glLoadIdentity()

        glEnable(GL_TEXTURE_2D)

        #caliculate the tex coords correspoinding to each index
        #since we force 128x128 image,
        glBindTexture(GL_TEXTURE_2D, self.tex.id)
        w = h = Puzzle.tex_size
        size = self.size
        tw = float(w)/size
        tc= ()
        for i in xrange(len(self.indices)):
            x = self.indices[i] % size
            y = self.indices[i] / size
            im_x1 = x * tw 
            im_y1 = y * tw

            im_x2 = (x+1) * tw
            im_y2 = (y+1) * tw

            t_x1 = im_x1/w
            t_y1 = im_y1/h
            t_x2 = im_x2/w
            t_y2 = im_y2/h
            tc+= (t_x1, t_y1, t_x2, t_y1, t_x2, t_y2, t_x1, t_y2)
#        pyglet.graphics.draw(len(self.verts)/2, GL_POLYGON, ('v2f', self.verts), ('t2f', tc))
#        pyglet.graphics.draw(len(self.verts)/2, GL_POLYGON, ('v2f', self.verts))
        for i in xrange(len(self.verts)/8):
            indx = i * 4 * 2
            if i == Puzzle.start:
                glColor3f(0, 1, 0)
                glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)
                glDisable(GL_TEXTURE_2D)
                glBegin(GL_POLYGON)
                glVertex2i(self.verts[indx], self.verts[indx+1])
                glVertex2i(self.verts[indx+2], self.verts[indx+3])
                glVertex2i(self.verts[indx+4], self.verts[indx+5])
                glVertex2i(self.verts[indx+6], self.verts[indx+7])
                glEnd()
                glEnable(GL_TEXTURE_2D)
                glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)

            glColor3f(1, 1, 1)
            glBegin(GL_POLYGON)
            glTexCoord2f(tc[indx], tc[indx+1])
            glVertex2i(self.verts[indx], self.verts[indx+1])
            glTexCoord2f(tc[indx+2], tc[indx+3])
            glVertex2i(self.verts[indx+2], self.verts[indx+3])
            glTexCoord2f(tc[indx+4], tc[indx+5])
            glVertex2i(self.verts[indx+4], self.verts[indx+5])
            glTexCoord2f(tc[indx+6], tc[indx+7])
            glVertex2i(self.verts[indx+6], self.verts[indx+7])
            glEnd()

        glDisable(GL_TEXTURE_2D)
        glMatrixMode(GL_PROJECTION)
        glPopMatrix()
        glMatrixMode(GL_MODELVIEW)
        glPopMatrix()

        self.head_msg.draw()
        self.tip.draw()

#w = pyglet.window.Window(800, 600)
#p = Puzzle(3) 
#start = -1
#stop = -1
#
#@w.event
#def on_mouse_press(x, y, button, modifiers):
#    global start
#    if pyglet.window.mouse.LEFT:
#        indx = p.getIndex((x-300, y-200))
#        print indx
#        start = indx
#
#@w.event
#def on_mouse_release(x, y, button, modifiers):
#    global start, stop
#    if pyglet.window.mouse.LEFT:
#        indx = p.getIndex((x-300, y-200))
#        print indx
#        stop = indx
#        if start > -1 and stop > -1 and not(start == stop):
#            p.swapIndices(start, stop)
#            if p.isSolved():
#                print "Solved!!!"
#        start = -1
#        stop = -1
#     
#@w.event
#def on_draw():
#    w.clear()
#
#    p.draw()
#
#pyglet.app.run()
